package com.zw.pdm.module.report.service;

import com.zw.pdm.constant.Constant;
import com.zw.pdm.entity.rep.*;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.designtask.service.DsnIssueService;
import com.zw.pdm.module.report.mapper.ChangeMapper;
import com.zw.pdm.module.report.mapper.PlanMapper;
import com.zw.pdm.module.report.mapper.SheetMapper;
import com.zw.pdm.module.report.mapper.VerifyProcessMapper;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.report.model.SheetModel;
import com.zw.pdm.module.report.repository.ChangeRepository;
import com.zw.pdm.module.report.repository.PlanRepository;
import com.zw.pdm.module.report.repository.SheetRepository;
import com.zw.pdm.module.report.repository.VerifyProcessRepository;
import com.zw.pdm.module.system.mapper.UserMapper;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static com.zw.pdm.util.BeanUtil.copy;


/**
 * @Description:
 * @Author: China.sgl
 * @Date: 2019/12/6 08:42
 */
@Service
@SuppressWarnings("all")
public class ReportCheckService {

    @Autowired
    private SheetMapper sheetMapper;
    @Autowired
    private SheetRepository sheetRepository;
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private PlanRepository planRepository;
    @Autowired
    private VerifyProcessMapper verifyProcessMapper;
    @Autowired
    private VerifyProcessRepository verifyProcessRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChangeRepository changeRepository;
    @Autowired
    private ChangeMapper changeMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private DsnIssueService dsnIssueService;

    /**
     * 按条件查询计划单
     */
    public List<SheetModel> findWithReportCheck(SheetModel sheet) {
        sheet.setVerifier(ShiroUtils.getUserId());
        return sheetMapper.findWithReportCheck(sheet);
    }

    /**
     * 审核计划
     */
    @Transactional(rollbackFor = Exception.class)
    public int verify(Integer id) {
        VerifyProcess vp = verifyProcessMapper.findCurVpBySheetId(id);
        if (vp.getComp() == 1) {
            // 如果是最后一步审核， 修改计划单状态， 添加或更新reportResult表
            // 修改，添加一个确认流程，后来又取消了
            Sheet sheet = sheetRepository.getOne(id);
            sheet.setStatus(Constant.STATUS_COMPLETE);
            sheet.setMayChange(1);
            sheetRepository.saveAndFlush(sheet);
            /** 20210407 update by wsg 首次下达时更新销售系统project项目表dsn_issue_status（设计图纸下发状态 0=未下发，1=已下发）为已下发状态*/
            List<Project> projects = dsnIssueService.findProjectByProCode(sheet.getProCode());
            if (projects != null && (projects.get(0).getDsnIssueStatus().compareTo(0) == 0)){
                dsnIssueService.editIssueStatus(projects.get(0).getCode(),1);
            }
            /**判断
             * 1 成本中心数据和不需要生产的数据插入或更新 rep_result表，项目数据不操作rep_result表 由生产系统处理
             * 2 原材料、外协件，直接进入rep_result表
             * **/
            Integer cCount = sheetMapper.findVCostCountByProCode(sheet.getProCode());// 成本中心数据
            Integer dCount = sheetMapper.findNotProduceCountByProCode(sheet.getProCode());// 不需要生产数据
            if (cCount.compareTo(0) == 1 || dCount.compareTo(0) == 1 || sheet.getReportType() == 2 || sheet.getReportType() == 3) {
                if (sheet.getSheetType() == 1) {
                    sheetMapper.insertResult(id);
                } else if (sheet.getSheetType() == 2) {
                    changeMapper.updateResultByChangeAfter(id);
                }
            }
        } else {
            // 修改下一个审核节点为当前节点
            VerifyProcess nextVp = verifyProcessMapper.findNextVp(vp);
            nextVp.setCur(1);
            verifyProcessRepository.saveAndFlush(nextVp);
        }
        logService.saveLog("审核计划单", "计划单ID：" + vp.getSheetId());
        return verifyProcessMapper.updateStatusAndCurAndTimeById(vp.getId(), 2, 0, new Date());
    }

    /**
     * 驳回计划
     */
    @Transactional(rollbackFor = Exception.class)
    public int reject(Sheet sheet) {
        VerifyProcess vp = verifyProcessMapper.findCurVpBySheetId(sheet.getId());
        logService.saveLog("驳回计划单", "计划单ID：" + vp.getSheetId());
        Sheet target = sheetRepository.getOne(sheet.getId());
        copy(sheet, target);
        if (vp.getStart() == 1) {
            // 如果为第一个审核节点，修改计划为未提交，删除所有审核结点
            target.setStatus(Constant.STATUS_REJECT);
            target.setCommitTime(null);
            sheetRepository.saveAndFlush(target);
            return verifyProcessMapper.delBySheetId(sheet.getId());
        } else {
            // 修改上一个审核节点为当前节点，并标识为驳回状态
            sheetRepository.saveAndFlush(target);
            VerifyProcess preVp = verifyProcessMapper.findPreVp(vp);
            preVp.setCur(1);
            preVp.setStatus(0);
            verifyProcessRepository.saveAndFlush(preVp);
            return verifyProcessMapper.updateStatusAndCurAndTimeById(vp.getId(), 1, 0, null);
        }
    }

    /**
     * 修改审核人
     */
    public VerifyProcess editVerify(VerifyProcess verifyProcess) {
        VerifyProcess vp = verifyProcessRepository.getOne(verifyProcess.getId());
        VerifyProcess nextVp = verifyProcessMapper.findNextVp(vp);
        nextVp.setVerifier(verifyProcess.getVerifier());
        logService.saveLog("修改审核人", "");
        return verifyProcessRepository.saveAndFlush(nextVp);
    }

    /**
     * 修改上级审核人（制作件清单）
     * @param sheet
     * @return
     */
    public VerifyProcess editMakeVerify(VerifyProcess verifyProcess) {
        VerifyProcess vp = verifyProcessRepository.getOne(verifyProcess.getId());
        VerifyProcess nextMakeVp = verifyProcessMapper.findMakeNextVp(vp);
        nextMakeVp.setVerifier(verifyProcess.getVerifier());
        logService.saveLog("修改审核人", "");
        return verifyProcessRepository.saveAndFlush(nextMakeVp);
    }

    public Sheet editSecondUser(Sheet sheet) {
        Sheet sheet1 = sheetRepository.getOne(sheet.getId());
        sheet1.setCreateId(sheet.getCreateId());
        User user = userMapper.findById(sheet.getCreateId());
        sheet1.setCreateName(user.getName());
        sheet1.setCreateCode(user.getAccount());
        return sheetRepository.saveAndFlush(sheet1);
    }

    /**
     * 查询部级审核人
     */
    public List<User> findVerifier() {
        return userMapper.findVerifier("部级");
    }

    public List<User> findSecondUser() {

        return userMapper.findInformant("员工级", ShiroUtils.getUser().getDeptId());
    }

    /**
     * 查询提报人
     */
    public List<User> findInformant() {
        return userMapper.findInformant("员工级", ShiroUtils.getUser().getDeptId());
    }

    /**
     * 撤消变更计划，
     * 如果所属主表下所有计划全部撤消， 要删除主表数据
     * 撤消的变更原始计划或原始变更还应该可以再次发起变更
     */
    @Transactional
    public int cancelChange(Integer id) {
        Change change = changeRepository.getOne(id);
        int i = changeMapper.updateResultByChangeBefore(change);
        if (i == 0) {
            return 0;
        }
        if (change.getChangeId() != null) {
            Change c = changeRepository.getOne(change.getChangeId());
            c.setAlreadyChange(0);
            changeRepository.saveAndFlush(c);
        } else if (change.getPlanId() != null) {
            Plan p = planRepository.getOne(change.getPlanId());
            p.setAlreadyChange(0);
            planRepository.saveAndFlush(p);
        }
        logService.saveLog("撤消变更计划", "变更计划ID：" + id);
        changeMapper.updateStatusById(id, 3);
        List<Change> changes = changeMapper.findBySheetId(change.getSheetId());
        if (changes.size() == 0) {
            sheetMapper.updateStatusById(change.getSheetId(), Constant.STATUS_DELETE);
        }
        return 1;
    }

    /**
     * 查询 变更详细
     */
    public List<Change> findChangeDetail(Change change) {
        return changeMapper.findChangeDetailList(change);
    }

    /**
     * 退回计划
     */
    public boolean returnSheet(Integer resultId) {
        planMapper.updateIsReturnByResultId(resultId);
        planMapper.deleteResultById(resultId);
        return true;
    }

}
